package com.aboo.infrastructure.base.domain.dto;

import com.aboo.infrastructure.base.constant.BaseConstant;
import com.aboo.infrastructure.base.enums.ErrEnum;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Result<T> implements Serializable {

    private String code;
    private String msg;
    private String timestamp;
    private T data;

    private Result() {
        super();
        this.timestamp = DateTimeFormatter.ofPattern(BaseConstant.DEFAULT_TIME_PATTERN).format(LocalDateTime.now());
    }

    public static Result<Void> success() {
        Result<Void> result = new Result<>();
        result.setErr(ErrEnum.ERR_000000);
        return result;
    }

    public static <U> Result<U> success(U data) {
        Result<U> result = new Result<>();
        result.setErr(ErrEnum.ERR_000000);
        result.setData(data);
        return result;
    }

    public static Result<Void> error() {
        Result<Void> result = new Result<>();
        result.setErr(ErrEnum.ERR_000001);
        return result;
    }

    public static Result<Void> error(ErrEnum error) {
        if (error == null) {
            return null;
        }
        Result<Void> result = new Result<>();
        result.setErr(error);
        return result;
    }

    private void setErr(ErrEnum error) {
        this.code = error.getValue();
        this.msg = error.getText();
    }

    private void setData(T data) {
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public T getData() {
        return data;
    }

    public boolean isSuccess() {
        return ErrEnum.ERR_000000.getValue().equals(this.code);
    }
}
